<template>
  <div class="container">
    <div class="display">
      <h2>Shopping Cart</h2>
      <div id="Cart">
        <form>
          <table>
            <tr>
              <th><b>Name</b></th>
              <th><b>Description</b></th>
              <th><b>Quantity</b></th>
              <th><b>List Price</b></th>
              <th><b>Total Cost</b></th>
              <th>&nbsp;</th>
            </tr>

            <tr v-if="cart.numberOfItems === 0">
              <td colspan="8"><b>Your cart is empty.</b></td>
            </tr>

            <tr v-if="cart.numberOfItems !== 0" v-for="cartItem in cart.cartItemList">
              <td v-text="cartItem.item.productId"></td>

              <td v-text="cartItem.item.attribute1"></td>

              <td>
                <input type="text" v-model="cartItem.quantity" v-text="cartItem.quantity" @input="updateQuantity" class="quantityNum">
              </td>

              <td>
                <span v-text="cartItem.item.listPrice"/>
              </td>
              <td>
                <p style="display: inline-block;">
                  <span v-text="cartItem.total"/>
                </p>
              </td>
              <td><a @click="removeItem(cartItem.item.itemId)" class="Button">Remove</a>
              </td>
            </tr>

            <tr>
              <td colspan="8">Sub Total:
                <span id="subtotal" style="display: inline-block;">
                  <span v-text="cart.subTotal"/>
                </span>
                <button type="button" @click="refreshCart" class="refreshButton"></button>
              </td>
            </tr>
          </table>
        </form>
      </div>

      <div id="draw-border" v-if="cart.numberOfItems > 0">
        <a class="ButtonNext" @click="newOrder" style="font-family: huayuan;position: relative;left: 160px;">
          <button>提交订单</button>
        </a>
      </div>


      <div id="Separator">&nbsp;</div>

      <div id="BackLink">
        <a @click="back">
          <button><span>返回</span></button>
        </a>
      </div>
    </div>

    <div id="MyList">
      <div v-if="banneropt===1">
        <include-my-list/>
      </div>
    </div>

  </div>
</template>

<script>
import IncludeMyList from "@/components/includeMyList";
import axios from 'axios'

export default {
  name: "cart",
  components: {IncludeMyList},
  data() {
    return {
      username: localStorage.getItem('username'),
      //购物车
      cart: {
        "cartItems": [],
        "numberOfItems": 0,
        "subTotal": 0,
        "cartItemList": [],
        "allCartItems": []
      },
      account: '',
      banneropt:null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      //更新cart
      const cartStr = localStorage.getItem('cart')
      this.cart = JSON.parse(cartStr)
      console.log(this.cart)
      console.log(cartStr)

      //存入account
      if(localStorage.getItem('account')!=null){
        const account = localStorage.getItem('account')
        this.account = JSON.parse(account)
        this.banneropt = account.banneropt
        console.log(this.account)
      }else{
        this.banneropt=0
      }
    },

    updateQuantity(e) {
      //修改数量
      const { value } = e.target;
      console.log("检测到变化"+value);
      const cart = this.cart
      const cartStr = JSON.stringify(cart)
      console.log(cart)
      axios({
        url: "http://127.0.0.1:8088/cart/updateCart",
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
        },
        data: cartStr
      }).then(res=>{
        console.log(res.data.data)
        const cart = res.data.data
        localStorage.setItem('cart', JSON.stringify(cart))
        this.init()
      })


    },
    //删除item
    removeItem(itemId) {
      const cartStr = localStorage.getItem('cart')
      console.log(cartStr)
      axios({
        url: "http://127.0.0.1:8088/cart/removeCartItem/" + itemId,
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
        },
        data: cartStr
      }).then(res => {
        console.log(res.data.data)
        const cart = res.data.data
        localStorage.setItem('cart', JSON.stringify(cart))
        this.init()
      })
    },
    //生成新订单
    newOrder() {
      let username = this.username
      if (username == null || username === '') {
        window.confirm('请先登录！')
      } else {
        const cart = JSON.parse(localStorage.getItem('cart'))
        console.log(cart)
        axios({
          url: "http://localhost:8088/order/newOrderForm/" + this.username,
          method: 'post',
          headers: {
            'Content-Type': 'application/json',
          },
          data: cart
        }).then(res => {
          //存放新订单
          console.log('newOrder' + res.data.data)
          let newOrderStr = JSON.stringify(res.data.data)
          localStorage.setItem('newOrder', newOrderStr)
          //初始化购物车
          let cartStr = JSON.stringify({
            "cartItems": [],
            "numberOfItems": 0,
            "subTotal": 0,
            "cartItemList": [],
            "allCartItems": []
          })
          localStorage.setItem('cart', cartStr)
          this.$router.push('/newOrderForm')
        })
      }
    },
    // 返回上一页
    back() {
      this.$router.go(-1)
    },
    //重置购物车
    refreshCart() {
      window.confirm('确定重置购物车？')
      //重置购物车
      const cart = {
        "cartItems": [],
        "numberOfItems": 0,
        "subTotal": 0,
        "cartItemList": [],
        "allCartItems": []
      }
      //生命周期是永久，除非主动清除localStorage信息，否则这些信息将一直存放在客户端
      localStorage.removeItem('cart')
      localStorage.setItem('cart', JSON.stringify(cart))
      location.href = '/cartForm'
    }
  }

}
</script>

<style scoped>
@import "../../assets/css/shop.css";

@font-face {
  font-family: 'cm';
  src: url("../../assets/font/Begilas.otf");
}

@font-face {
  font-family: 'huayuan';
  src: url("../../assets/font/花园肉丸.ttf");
}

.display {
  margin: 0 auto;
  top: 120px;
}

#BackLink {
  margin: 0 auto;
  position: absolute;
  left: 50%;
  top: 94%;
  transform: translate(-50%, -50%);
}

.refreshButton {
  width: 20px;
  height: 20px;
  margin-left: 20px;
  background-image: url('../../assets/img/refresh.png');
  background-repeat: no-repeat;
  background-size: contain;
  background-color: inherit;
  border: none;
  cursor: pointer;
}

td input {
  width: 30px;
  text-align: center;
}
</style>